package com.yyhh.helpcall.activity;

import androidx.appcompat.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.Html;
import android.text.Spanned;
import android.view.View;
import android.widget.TextView;
import com.yyhh.helpcall.MainApplication;
import com.yyhh.helpcall.R;
import com.yyhh.helpcall.http.OkHttpUtils;
import com.yyhh.helpcall.http.bean.BaseResponse;
import com.yyhh.helpcall.http.bean.TellInfosRsponse;
import com.yyhh.helpcall.server.AppService;
import com.yyhh.helpcall.utils.AppUtils;
import com.yyhh.helpcall.utils.HuaWeiUtils;
import com.yyhh.helpcall.utils.NetLog;
import com.yyhh.helpcall.utils.ScanRecordUtils;
import com.yyhh.helpcall.utils.SpUtils;
import com.yyhh.helpcall.utils.ToastUtils;
import java.util.HashMap;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends BaseActivity {

    private TextView todayTotal, todayIncomingCount, todayOutgoingCount, allTotal, allIncomingTime, allOutgoingTime;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 400:
                    startCallServer();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
        checkEnableRecords();
        checkDrawOverlaysPermission();
        startCallServer();

    }

    private void startCallServer(){
        HuaWeiUtils.initHuaWeiToken(getApplicationContext());
        //启动后台服务
        Intent intent = new Intent(MainActivity.this, AppService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent);
        } else {
            startService(intent);
        }
    }

    private void checkDrawOverlaysPermission() {
        //申请悬浮窗权限
        if (Build.VERSION.SDK_INT >= 23) { // Android6.0及以后需要动态申请权限
            if (!Settings.canDrawOverlays(this)) {
                new AlertDialog.Builder(this)
                        .setTitle("温馨提示")
                        .setMessage("请开启悬浮窗权限,避免您无法正确使用某些功能")
                        .setCancelable(false)
                        .setPositiveButton("前往开启", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //启动Activity让用户授权
                                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
                                startActivityForResult(intent, 1010);
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .create()
                        .show();
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        NetLog.d("MainActivity onNewIntent");
        boolean isLoginOut = intent.getBooleanExtra("isLoginOut", false);
        boolean isNewLogin = intent.getBooleanExtra("isNewLogin", false);

        if (isLoginOut) {
            //停止后台服务
            stopService(new Intent(MainActivity.this, AppService.class));
            SpUtils.getInstance(MainApplication.mainApplication).putString("account", "");
            SpUtils.getInstance(MainApplication.mainApplication).putString("token", "");

            //移除别名
            JPushInterface.deleteAlias(getApplicationContext(),1);
            HuaWeiUtils.deleteHuaWeiToken(getApplicationContext());

            startActivity(new Intent(this, LoginActivity.class));
            finish();
        } else if(isNewLogin){
            //停止后台服务
            stopService(new Intent(MainActivity.this, AppService.class));
            HuaWeiUtils.deleteHuaWeiToken(getApplicationContext());
            //重新启动
            handler.sendEmptyMessageDelayed(400,1000 * 5);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        initDatas();
    }

    private void initViews() {
        TextView brand = findViewById(R.id.brand);
        TextView model = findViewById(R.id.model);
        TextView versionName = findViewById(R.id.versionName);
        brand.setText(Build.BRAND);
        model.setText(Build.MODEL);
        versionName.setText(AppUtils.getVersionName(this));

        todayTotal = findViewById(R.id.todayTotal);
        todayIncomingCount = findViewById(R.id.todayIncomingCount);
        todayOutgoingCount = findViewById(R.id.todayOutgoingCount);
        allTotal = findViewById(R.id.allTotal);
        allIncomingTime = findViewById(R.id.allIncomingTime);
        allOutgoingTime = findViewById(R.id.allOutgoingTime);


        findViewById(R.id.calllogs).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, CallLogsActivity.class));
            }
        });
        findViewById(R.id.records).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, RecordsActivity.class));
            }
        });
        findViewById(R.id.bottom).setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                startActivity(new Intent(MainActivity.this,TestActivity.class));
                return true;
            }
        });
        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                moveTaskToBack(true);
            }
        });
        findViewById(R.id.switchAccount).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, LoginActivity.class));
            }
        });
        findViewById(R.id.settings).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,SettingActivity.class));
            }
        });
        findViewById(R.id.exit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, MainActivity.class);
                intent.putExtra("isLoginOut",true);
                startActivity(intent);
            }
        });
    }

    private void initDatas() {
        OkHttpUtils.getInstance().getApi()
                .getTellInfos(new HashMap<>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResponse<TellInfosRsponse>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseResponse<TellInfosRsponse> value) {
                        if (value.isSuccess()) {

                            allTotal.setText(value.data.all_tel_total_time);
                            allIncomingTime.setText(fromHtml(value.data.all_tel_total_time_1,value.data.all_tel_total_1,true));
                            allOutgoingTime.setText(fromHtml(value.data.all_tel_total_time_0,value.data.all_tel_total_0,false));

                            todayTotal.setText(value.data.tel_total_time);
                            todayIncomingCount.setText(fromHtml(value.data.tel_total_time_1,value.data.tel_total_1,true));
                            todayOutgoingCount.setText(fromHtml(value.data.tel_total_time_0,value.data.tel_total_0,false));

                        } else {
                            value.showErrorMessage();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        ToastUtils.show("出现错误,请重试~");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 格式化字符串模板
     * @param incomingCount
     * @param outgoingCount
     * @return
     */
    public Spanned fromHtml(String incomingCount,String outgoingCount,boolean isIncomingCount){
        String text1 = isIncomingCount ? "呼入" : "呼出";
        String text2 = "<font color='#FC3737'>" + incomingCount + "</font>";
        String text3 = "分钟   ";
        String text4 =  "<font color='#FC3737'>" + outgoingCount + "</font>";
        String text5 = "个电话";

        return Html.fromHtml(text1 + text2 + text3 + text4 + text5);
    }

    /**
     * 检测通话功能是否开启
     */
    private void checkEnableRecords() {
        //检测是否开启录音权限
        ScanRecordUtils.checkEnableRecords(this, new ScanRecordUtils.EnableRecordsCallBack() {
            @Override
            public void onSuccess(boolean enable) {
                if (enable) {
                    //ToastUtils.show("你已经开启了通话录音功能");
                } else {
                    new AlertDialog.Builder(MainActivity.this)
                            .setTitle("温馨提示")
                            .setMessage("系统检测到您可能没有开启通话录音功能,如已开启请忽略该提示")
                            .setCancelable(false)
                            .setPositiveButton("帮助中心", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(MainActivity.this, PublicWebViewActivity.class);
                                    String wd = Build.BRAND + "手机如何开启通话录音";
                                    intent.putExtra("url", "http://www.baidu.com/s?wd=" + wd);
                                    startActivity(intent);
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            })
                            .create()
                            .show();
                }
            }

            @Override
            public void onFail(Throwable e) {

            }
        });
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
